package com.cipe.cmrs.util;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.cipe.cmrs.model.Role;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.model.ref.Link;

public enum UserUtil {
    INSTANCE;

    /**
     * 
     * @return User object of current user
     */
    public User getCurrentUser() {
        SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx == null || ctx.getAuthentication() == null) {
            return null;
        }
        if (ctx.getAuthentication() == null) {
            return null;
        }

        User user = null;
        if (ctx.getAuthentication() instanceof User) {
            user = (User) ctx.getAuthentication();
        } else if (ctx.getAuthentication().getPrincipal() instanceof User) {
            /*
             * if authentication-provider (DaoAuthenticationProvider) in
             * security.xml is used.
             */
            user = (User) ctx.getAuthentication().getPrincipal();
        }

        return user;
    }

    public Set<Link> getCurrentUserAllowedLinks() {
        HashSet<Link> links = new HashSet<Link>();
        User user = getCurrentUser();
        if (user.getRoles() != null) {
            for (Role role : user.getRoles()) {
                links.addAll(role.getLinks());
            }
        }
        return links;
    }
    
    public boolean hasAnyRoles(List<String> roles) {
        boolean result = false;
        List<String> list = getCurrentUser().getRoleNames();
        for (String role : roles) {
            if (list.contains(role)) {
                result = true;
                break;
            }
        }
        return result;
    }
    
    public boolean isSecurePassword(String password) {
    	if (password.length() < 8) {
    		return false;
    	}

    	int counter = 0;
    	boolean foundUpperCase = false;
    	boolean foundLowerCase = false;
    	boolean foundDigit = false;
    	boolean foundSymbol = false;
    	for (char c : password.toCharArray()) {
    		if (Character.isLetter(c)) {
    			if (Character.isUpperCase(c)) {
    				if (!foundUpperCase) {
    					foundUpperCase = true;
    					counter++;
    				}
    			} else if(Character.isLowerCase(c)) {
    				if (!foundLowerCase) {
    					foundLowerCase = true;
    					counter++;
    				}
    			}
    		} else if(Character.isDigit(c)) {
				if (!foundDigit) {
					foundDigit = true;
					counter++;
				}
    		} else if (!foundSymbol) {
    			foundSymbol = true;
    			counter++;
    		}
    		if (counter >= 3) {
    			return true;
    		}
    	}
    	return false;
    }
}
